package com.handydata.antifraud.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import com.handydata.antifraud.common.exception.AlarmInfoExCode;
import com.handydata.common.exception.SysException;

@Component
public class MailUtil {

    private Logger logger = LoggerFactory.getLogger(MailUtil.class);

    @Autowired
    private JavaMailSender javaMailSender; //框架自带的

    @Value("${spring.mail.username}")  //发送人的邮箱  比如155156641XX@163.com
    private String from;
    @Value("${spring.mail.enable:true}")  //发送人的邮箱  比如155156641XX@163.com
    private boolean enable;

    //@Async  //意思是异步调用这个方法
    public void sendMail(String title, String content, String email) throws SysException{
        sendMail(title,content,new String[]{email});
    }
    //@Async  //意思是异步调用这个方法
    public void sendMail(String title, String content, String[] email) throws SysException {
        if(enable){
            try{
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(from); // 发送人的邮箱
                message.setSubject(title); //标题
                message.setTo(email); //发给谁  对方邮箱
                message.setText(content); //内容
                javaMailSender.send(message); //发送
            }catch (Exception ex){
                logger.error("发送邮件异常{}" ,title,ex);
                throw  new SysException(AlarmInfoExCode.SYS_SEND_EMAIL_ERROR);
            }
        }else {
            logger.error("邮件配置没有启用，却有消息要发送{}",content);
        }


    }
}
